<template>
  <div class="map" ref="mapDiv"></div>
  <LayersSelected v-if="showPanle" />
  <BaseMap v-if="showPanle" />
  <Measure v-if="showPanle" :map="mapView" />
</template>

<script setup>
import Tianditu from '@/utils/maplayer/Tianditu';
import { Map, View } from 'ol';
import { fromLonLat } from 'ol/proj';
import { shallowRef, ref, onMounted } from 'vue';

import loadWFSLayer from '@/utils/maplayer/wfsLayer';
import loadWMSLayer from '@/utils/maplayer/wmsLayer';
import getWMSInfo from '@/utils/mapLayerInfo/getWMSInfo';
// 组件
import LayersSelected from '@/components/LayersSelected.vue';
import BaseMap from '@/components/BaseMap.vue';
import Measure from '@/components/Measure.vue';


import Test from '@/components/popup/Test.vue';
import Popup from '@/utils/popup/popup.js';

import { useLayersStore } from '@/stores/layers';
import { useBaseLayersStore } from '@/stores/baseLayers';
// 地图容器
const mapDiv = ref()
let mapView = shallowRef()
// 初始化地图
const baseLayersStore = useBaseLayersStore()
const TDT = new Tianditu()
const vecLyrGrp = TDT.createTileLayerGroup('vec', true)
const imgLyrGrp = TDT.createTileLayerGroup('img', false)
baseLayersStore.baseLayers.push(["矢量地图", vecLyrGrp])
baseLayersStore.baseLayers.push(["影像地图", imgLyrGrp])


// 地图组件
const showPanle = ref(false)
// 业务图层列表
const layersStore = useLayersStore()
onMounted(async() => {
  createMap()
  const wfsLayer = await loadWFSLayer(mapView.value)
  layersStore.layers.push(["wfs", wfsLayer])
  // 加载业务图层
  let wms = loadWMSLayer(mapView.value, 'fm')
  layersStore.layers.push(["阀门", wms])
  let gx = loadWMSLayer(mapView.value, 'gx')
  layersStore.layers.push(["管线", gx])
  // 获取阀门信息
  mapView.value.on('singleclick', async (event) => {
    const featureData = await getWMSInfo(event, mapView.value, wms)
    if (featureData.features[0]) {
      const point =  featureData.features[0].geometry.coordinates;
      const options = {
        component: Test,
        coordinate: point,
        content: featureData
      }
      new Popup(options, mapView.value, false)
    }

    
  });

  // 当主地图所有都初始化完成时，开启相关面板
  showPanle.value = true
})

function createMap() {
  mapView.value = new Map({
    target: mapDiv.value,
    layers: [vecLyrGrp, imgLyrGrp],
    controls: [],
    view: new View({
      center: fromLonLat([119.28, 26.08]),
      zoom: 12,
      projection:"EPSG:3857",
    }),
  })
}

// 监听map渲染其它组件
// watch(mapView, (newMapView) => {
//   if (newMapView.value !== null) {
//     showPanle.value = true
//   }
// })
</script>

<style scoped>
.map {
  width: 100vw;
  height: 100vh;
}
</style>
